<template>
  <div class="main">
    <div class="login-rect">
      <div class="banner-posi">
        <a-carousel class="carousel">
          <a-carousel-item>
            <img src="@/assets/img/login/login1.jpg" alt="">
          </a-carousel-item>
          <a-carousel-item>
            <img src="@/assets/img/login/login2.jpg" alt="">
          </a-carousel-item>
        </a-carousel>
      </div>
      <div class="login-form">
        <img src="@/assets/Logo.svg" class="logo" alt="">
        <span class="login-title">顺丰发票管理系统</span>
        <a-form :model="loginForm.form" :rules="loginForm.rules" layout="vertical" ref="loginFormRef">
          <a-form-item label="账号" field="username">
            <a-input v-model="loginForm.form.username"></a-input>
          </a-form-item>
          <a-form-item label="密码" field="password">
            <a-input-password v-model="loginForm.form.password" allow-clear
                              @pressEnter="formValidate"></a-input-password>
          </a-form-item>
          <!--          <a-form-item label="验证码">-->
          <!--            <a-input v-model="loginForm.form.password" allow-clear @pressEnter="formValidate"></a-input>-->
          <!--            <img class="captcha-img" :src="captchaImg" @click="getCapture" alt="">-->
          <!--          </a-form-item>-->
          <a-form-item>
            <a-checkbox v-model="loginForm.form.rememberMe">记住密码</a-checkbox>
          </a-form-item>
          <a-button type="primary" @click="formValidate">登 录</a-button>
          <!--          <a-button type="text" @click="register">注 册</a-button>-->
        </a-form>
      </div>

      <register-dialog ref="registerRef"></register-dialog>

      <a-modal v-model:visible="changePassVisible" title="更改密码" :on-before-ok="changePass">
        <a-alert type="success" style="margin-bottom: 10px;">欢迎使用本系统，第一次使用请重置密码。密码长度不少于6位，且包含英文和数字</a-alert>
        <a-form :model="changePassForm" ref="changePasswordRef" :rules="changePassRules">
          <a-form-item field="password" label="输入新密码">
            <a-input-password v-model="changePassForm.password"></a-input-password>
          </a-form-item>
          <a-form-item field="confirmPass" label="确认密码">
            <a-input-password v-model="changePassForm.confirmPass"></a-input-password>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted} from 'vue';
import {Form} from '@arco-design/web-vue'
import {Message} from '@arco-design/web-vue'
import {activeAccount, login, User} from '@/api/sysController'
import router from "@/router";
import {userStore} from "@/store/user.ts";
import RegisterDialog from "@/views/login/registerDialog.vue";
import axios from "axios";
import {useRoute} from "vue-router";


const registerRef = ref()
const route = useRoute()

const changePassVisible = ref(false)

onMounted(() => {
  const rememberMe = userStore().rememberMe;
  if (rememberMe.username) {
    loginForm.form.username = rememberMe.username
    loginForm.form.password = rememberMe.password
    loginForm.form.rememberMe = true
  }
})

const loginFormRef = ref<InstanceType<typeof Form>>()
const loginForm = reactive({
  form: {
    username: '',
    password: '',
    rememberMe: false
  },
  rules: {
    username: [{required: true, message: '请输入账号'}],
    password: [{required: true, message: '请输入密码'}]
  }
})

const waitToStore = ref()

const formValidate = async () => {

  let errResult
  await loginFormRef.value?.validateField(['username', 'password'], (err) => {
    console.log(err, 'err');
    errResult = err
  })
  if (!errResult) {
    const res: any = await login(loginForm.form.username, loginForm.form.password)

    console.log(res, 'loginRes')
    if (res.status === '初始化') {
      changePassVisible.value = true
      waitToStore.value = res
      return
    }

    if (loginForm.form.rememberMe) {
      userStore().setRememberMe(loginForm.form.username, loginForm.form.password)
    } else {
      userStore().setRememberMe('', '')
    }
    console.log(route, 'redirectUrl')
    const redirectUrl = route.query?.redirectUrl
    if (redirectUrl) {
      window.location.href = redirectUrl
    } else {
      router.push('/')
    }
    Message.success('登录成功')
    console.log(res)
    userStore().setUserInfo(res as User)
  } else {
    Message.error('请检查用户名和密码是否填写完成')
  }
}

const register = () => {
  console.log(registerRef.value, 'ref');
  registerRef.value.open()
}

const changePasswordRef = ref()

const changePassForm = reactive({
  password: '',
  confirmPass: ''
})

const changePassRules = {
  password: [{required: true, message: '请输入密码'},
    {
      minLength: 6, message: '密码长度不少于6位'
    }, {
      match: /(?=.*[0-9])(?=.*[a-zA-Z]).*/, message: '密码需同时含有英文和数字'
    }],
  confirmPass: [{required: true, message: '请确认密码'},
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if(value === changePassForm.password) {
          callback()
        } else {
          callback('两次输入密码不一致，请检查')
        }
      }
    }]
}

const changePass = (done) => {
  changePasswordRef.value.validate((error) => {
    console.log(error, 'err')
    if(error) {
      done(false)
    } else {
      activeAccount(changePassForm.password).then(res => {
        if (loginForm.form.rememberMe) {
          userStore().setRememberMe(loginForm.form.username, loginForm.form.password)
        } else {
          userStore().setRememberMe('', '')
        }
        Message.success('登录成功')
        userStore().setUserInfo(waitToStore as User)

        router.push('/welcome')
      })
    }
  })
}

</script>

<style lang="scss" scoped>
.main {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(180deg, rgb(213, 234, 255) 0%, rgba(161, 216, 255, 1) 100%);
  display: flex;
  align-items: center;

  .login-rect {
    display: flex;
    left: 476px;
    top: 65px;
    width: 1024px;
    height: 651px;
    margin: auto;
    border-radius: 8px;
    overflow: hidden;
    background: rgba(255, 255, 255, 1);

    .captcha-img {
      width: 80px;
      margin-left: 10px;
    }

    .banner-posi {
      position: relative;
      width: 50%;
      height: 100%;
      background-color: #165dff;

      .carousel {
        width: 100%;
        height: 100%;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .login-form {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 300px;
      margin: auto;

      .login-title {
        display: inline-block;
        width: 100%;
        font-size: 20px;
        font-weight: bold;
        text-align: center;
        margin: 20px auto;
      }

      .logo {
        width: 80px;
      }
    }
  }
}

@media (max-width: 768px) {
  .login-rect {
    .banner-posi {
      display: none;
    }
  }
}
</style>
